<template>
  <div>
    <a-button
      type="primary"
      icon="plus"
      @click="handleAdd"
      style="margin-bottom:15px">新建</a-button>
    <a-button
      type="primary"
      icon="dowload"
      @click="handleDownload"
      style="margin-bottom:15px;margin-left:15px;">导出</a-button>
    <a-table
      :columns="columns"
      :data-source="list"
      bordered>

      <div
        slot="filterDropdown"
        slot-scope="{ setSelectedKeys, selectedKeys, confirm, clearFilters, column }"
        style="padding: 8px">
        <a-input
          v-ant-ref="c => (searchInput = c)"
          :placeholder="`Search ${column.dataIndex}`"
          :value="selectedKeys[0]"
          style="width: 188px; margin-bottom: 8px; display: block;"
          @change="e => setSelectedKeys(e.target.value ? [e.target.value] : [])"
          @pressEnter="() => handleSearch(selectedKeys, confirm, column.dataIndex)" />
        <a-button
          type="primary"
          icon="search"
          size="small"
          style="width: 90px; margin-right: 8px"
          @click="() => handleSearch(selectedKeys, confirm, column.dataIndex)">
          查询
        </a-button>
        <a-button
          size="small"
          style="width: 90px"
          @click="() => handleReset(clearFilters)">
          重置
        </a-button>
      </div>
      <a-icon
        slot="filterIcon"
        slot-scope="filtered"
        type="search"
        :style="{ color: filtered ? '#108ee9' : undefined }" />
      <template
        v-for="col in cols"
        :slot="col"
        slot-scope="text, record">
        <div :key="col">
          <a-input
            v-if="record.editable"
            style="margin: -5px 0"
            :value="text"
            @change="e => handleChange(e.target.value, record.key, col)" />
          <template v-else>
            {{ text }}
          </template>
        </div>
      </template>
      <template
        slot="operation"
        slot-scope="text, record">
        <div class="editable-row-operations">
          <span v-if="record.editable">
            <a @click="() => save(record.key)">保存</a>
            <a-popconfirm
              title="Sure to cancel?"
              @confirm="() => cancel(record.key)">
              <a>取消</a>
            </a-popconfirm>
          </span>
          <span v-else>
            <a
              :disabled="editingKey !== ''"
              @click="() => edit(record.key)"
              style="margin-right:5px">编辑</a>
            <a
              :disabled="editingKey !== ''"
              @click="() => handleDelete(record.key)">删除</a>
          </span>
        </div>
      </template>
    </a-table>
  </div>
</template>
<script>

export default {
  props: {
    'columns': {
      type: Array,
      default: () => []
    },
    'cols': {
      type: Array,
      default: () => []
    },
    'colsZh': {
      type: Array,
      default: () => []
    },
    'list': {
      type: Array,
      default: () => []
    },
    'methodRefs': {
      type: Object,
      default: () => {}
    }
  },
  data () {
    return {
      cacheData: [],
      editingKey: '',
      isAdd: false
    }
  },
  computed: {
    count () {
      return this.list.length
    }
  },
  methods: {
    handleChange (value, key, column) {
      const newData = [...this.list]
      const target = newData.filter(item => key === item.key)[0]
      if (target) {
        target[column] = value
        this.methodRefs.changeData(newData)
      }
    },
    handleAdd () {
      const { count, list } = this
      this.cacheData = list.map(item => ({ ...item }))
      const newData = {
        key: count,
        name: ``,
        genere: '',
        age: '',
        id: count,
        blood_sugar: ``,
        blood_pressure: ``
      }
      this.isAdd = true
      const newList = [newData, ...list]
      this.list = newList
      this.edit(newData.key)
    },
    edit (key) {
      const newData = [...this.list]
      const target = newData.filter(item => key === item.key)[0]
      this.editingKey = key
      if (target) {
        target.editable = true
        this.methodRefs.changeData(newData)
      }
    },
    save (key) {
      const newData = [...this.list]
      const target = newData.filter(item => key === item.key)[0]
      if (!this.valid(target)) {
        this.cancel(key)
        return
      }
      this.editingKey = ''
      if (this.isAdd === true) {
        this.methodRefs.addData(target).then(res => {
          if (res.status === 0) {
            this.$message.info(res.msg)
          } else {
            this.$message.error(res.msg)
          }
          this.methodRefs.loadData()
        })
        this.isAdd = false
      } else {
        this.methodRefs.editData(target).then(res => {
          if (res.status === 0) {
            this.$message.info(res.msg)
          } else {
            this.$message.error(res.msg)
          }
          this.methodRefs.loadData()
        })
      }
    },
    cancel () {
      this.editingKey = ''
      this.methodRefs.changeData(this.cacheData)
    },
    handleDelete (key) {
      const newData = [...this.list]
      const deleteData = newData.filter(item => key === item.key)[0]
      const params = {
        _id: deleteData._id
      }
      this.methodRefs.deleteData(params).then(res => {
        if (res.status === 0) {
          this.$message.success(res.msg)
          this.methodRefs.loadData()
          // this.list = newData.filter(item => key !== item.key)
        } else {
          this.$message.error(res.msg)
        }
      })
    },
    handleSearch (selectedKeys, confirm, dataIndex) {
      confirm()
      this.searchText = selectedKeys[0]
      this.searchedColumn = dataIndex
    },
    handleReset (clearFilters) {
      clearFilters()
      this.searchText = ''
    },
    handleDownload () {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = this.colsZh
        const filterVal = this.cols
        const list = this.list
        const data = this.formatJson(filterVal, list)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: 'excel-list',
          autoWidth: true,
          bookType: 'xlsx'
        })
        this.downloadLoading = false
      })
    },
    formatJson (filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => {
        // if (j === 'timestamp') {
        //   return parseTime(v[j])
        // } else {
        //   return v[j]
        // }
        return v[j]
      }))
    },
    valid (patient) {
      if (patient.id === '') {
        this.$message.error('身份证号不能为空!')
        return false
      }
      if (patient.genere === '') {
        this.$message.error('性别不能为空!')
        return false
      }
      if (patient.name === '') {
        this.$message.error('姓名不能为空!')
        return false
      }
      const duplicateCount = this.list.filter(item => patient.id === item.id).length
      if (duplicateCount > 1) {
        this.$message.error('身份证号重复!')
        return false
      }
      return true
    }
  }
}
</script>
<style scoped>
.editable-row-operations a {
  margin-right: 8px;
}
.highlight {
  background-color: rgb(255, 192, 105);
  padding: 0px;
}
</style>
